'use strict';
import React from "react";
import {
    View,
    Image,
    Text,
    TouchableOpacity,
    StyleSheet,
    Dimensions,
    Animated,
    ActivityIndicator,
    InteractionManager
} from "react-native";
import Foreground from "../Components/Foreground";
import ParallaxScrollView from "react-native-parallax-scroll-view";
import FixedHeader from "../Components/FixedHeader";
import RenderShopItem from "../Components/RenderShopItem";
import CommentStarView from "../Components/CommentStarView";
import AllGoodsPage from "./AllGoodsPage";
import {_renderStar} from "../Utils/ViewUtils";
import ViewPager from "react-native-viewpager";
import InitiatedHelpToBuy from "./InitiatedHelpToBuy";
import SpecialtyDetailsPage from "./SpecialtyDetailsPage";
import BottomShareView from "../Components/BottomShareView";
import BottomCommentBtn from "../Components/BottomCommentBtn";
import RuralLibraryAPIService from "../Commom/RuralLibraryAPIService";
import Global from "../Commom/GlobalConst";
import ImageViewer from "./ImageViewer";
import Toast from "../Utils/toast";
import RegisteredContainer from '../Containers/RegisteredContainer';
let width = Dimensions.get('window').width;

const styles = StyleSheet.create({
    star: {
        width: 20,
        height: 20,
        marginRight: 5
    },
    btnBox: {
        marginRight: 5,
        borderRadius: 5,
        backgroundColor: '#38D68B',
        width: 60,
        height: 30,
        alignItems: 'center',
        justifyContent: 'center',
    },
    button: {
        color: 'white',
    },
    flexRow: {
        flexDirection: 'row',
        padding: 15,
        alignItems: 'center',
        borderTopWidth: 1,
        borderTopColor: '#F2F3F5'
    },
    tenBorderLine: {
        borderTopWidth: 15,
        borderTopColor: '#F2F3F5',
    },
    avatar: {
        width: 40,
        height: 40,
        marginRight: 5,
    },
    name: {
        flex: 1,
    },
    date: {
        textAlign: 'right',
        color: 'black',
    },
    rowContent: {
        flexDirection: 'row',
        alignItems: 'center',
        width: window.width - 10,
    }
});

/**
 * 农家有售
 */

class FarmHouseSell extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            flag: false,
            dataSource: new ViewPager.DataSource({
                pageHasChanged: (p1, p2) => p1 !== p2,
            }),
            introduce: {},
            commentList: [],
            shopList: [],
            paddingBottom: new Animated.Value(10),
            images: [],
            phone: '',
        }
    }

    componentDidMount() {
        // this.onFetch();
        let id = this.props.ID;
        if (!id) {
            id = 1;
        }
        InteractionManager.runAfterInteractions(() => {
            RuralLibraryAPIService.storeDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
                let introduce = {
                    id: ret.id,
                    title: ret.shop_name,
                    star: 4,
                    address: ret.address,
                };
                this.setState({
                    flag: true,
                    introduce,
                    shopList: ret.shop_list,
                    commentList: ret.comment_list,
                    images: ret.images,
                    phone: ret.phone,
                    dataSource: this.state.dataSource.cloneWithPages(ret.images),
                });
            }).catch((err)=> {

            });
        });
    }

    refreshComments() {
        let id = this.props.ID;
        if (!id) {
            id = 1;
        }
        RuralLibraryAPIService.storeDetails(Global.Const.token, Global.Const.registeredId, id).then((ret)=> {
            this.setState({
                commentList: ret.comment_list,
            });
        }).catch((err)=> {

        });
    }

    goToAllGoodsPage() {
        this.props.navigator.push({
            name: 'AllGoodsPage',
            component: AllGoodsPage,
            passProps: {
                ID: this.props.ID,
            }
        })
    }

    goToSpecialty(id) {
        this.props.navigator.push({
            name: 'SpecialtyDetailsPage',
            component: SpecialtyDetailsPage,
            passProps: {
                ID: id
            }
        })
    }

    goToHelpBuyPage() {
        if (Global.Const.token == '') {
            // Toast.show('请先登录！');
            this.props.navigator.push({
                id: 'RegisteredContainer',
                component: RegisteredContainer,
                passProps: {},
            });
            return;
        }
        this.props.navigator.push({
            name: 'InitiatedHelpToBuy',
            component: InitiatedHelpToBuy,
            passProps: {
                type: 2,
                id: this.props.ID,
            }
        })
    }

    viewPagerItemClick() {
        this.props.navigator.push({
            name: 'ImageViewer',
            component: ImageViewer,
            passProps: {
                source: this.state.images
            }
        })
    }

    _renderViewPager() {
        return (
            <View style={{height: 245,width,}}>
                {this.state.images.length > 1 ?
                    <ViewPager
                        locked={false}
                        isLoop={true}
                        autoPlay={true}
                        renderPageIndicator={false}
                        renderPage={(page) => {
                    return (
                        <TouchableOpacity onPress={() => this.viewPagerItemClick()}>
                            <Image source={{uri:page}}
                                   style={{
                                       height: 245,
                                       width,
                                   }}
                            />
                        </TouchableOpacity>
                    )
                }}
                        dataSource={this.state.dataSource}
                    /> :
                    <TouchableOpacity onPress={() => this.viewPagerItemClick()}>
                        <Image source={{uri:this.state.images[0]}}
                               style={{height: 245,width}}
                        />
                    </TouchableOpacity>}

            </View>
        )
    }

    _renderStickyHeader() {
        return (
            <View>
                <View style={{height: 55,paddingTop: 15,alignItems: 'center',justifyContent: 'center'}}>
                    <Text style={{color: "#333",fontSize: 18}}>{this.state.introduce.title}</Text>
                </View>
                <View style={{
                marginTop: 5,
                backgroundColor: 'white',
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                paddingRight: 15,
                paddingLeft: 15,
            }}>
                    <Text numberOfLines={1} style={{
                    fontSize: 16,
                    marginRight: 10,
                    textAlignVertical: 'center'
                }}>{this.state.introduce.title}</Text>
                    {_renderStar(this.state.introduce.star, {marginTop: 0})}
                    <TouchableOpacity style={styles.btnBox} onPress={() => {this.goToHelpBuyPage()}}>
                        <Text style={styles.button}>帮购</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }


    render() {
        return (
            <Animated.View
                style={{flex: 1,backgroundColor:Global.Const.transparent}}>
                {
                    this.state.flag ?
                        <ParallaxScrollView
                            showsVerticalScrollIndicator={false}
                            contentBackgroundColor={'white'}
                            backgroundColor={'white'}
                            headerBackgroundColor="#333"
                            stickyHeaderHeight={ 95 }
                            parallaxHeaderHeight={ 245 }
                            backgroundSpeed={10}
                            renderForeground={() => {
                                return (
                                    <Foreground
                                        height={245}
                                        renderHeader={() => this._renderViewPager()}
                                        size={this.state.dataSource.getPageCount()}
                                    />
                                )
                            }}
                            renderFixedHeader={()=> {
                                return (
                                    <FixedHeader rightFunc={()=> {
                                        this.shareView && this.shareView.showShareView();
                                    }} navigator={this.props.navigator}/>
                                )
                            }}
                            renderStickyHeader={()=> this._renderStickyHeader()}
                        >
                            <View style={styles.flexRow}>
                                <View style={{
                                    flex: 1
                                }}>
                                    <Text numberOfLines={1} style={{
                                        fontSize: 18,
                                        color: 'black',
                                    }}>{this.state.introduce.title}</Text>
                                    {_renderStar(this.state.introduce.star, {marginTop: 0})}
                                </View>
                                <TouchableOpacity style={styles.btnBox} onPress={() => {this.goToHelpBuyPage()
                                }}>
                                    <Text style={styles.button}>帮购</Text>
                                </TouchableOpacity>
                            </View>
                            <View style={styles.flexRow}>
                                <Image
                                    style={styles.star}
                                    source={require('../../Image/address_icon.png')}
                                    resizeMode={'contain'}
                                />
                                <Text style={{
                                    flex: 1
                                }}>{this.state.introduce.address}</Text>
                            </View>
                            <View style={styles.tenBorderLine}>
                                {
                                    this.state.shopList ?
                                        this.state.shopList.map((item, index) => {
                                            return (
                                                <RenderShopItem activeOpacity={0}
                                                                onItemPress={(id) => this.goToSpecialty(id)}
                                                                key={'shop' + index} {...item}/>
                                            )
                                        }) : null
                                }
                            </View>
                            <TouchableOpacity onPress={() => this.goToAllGoodsPage()}>
                                <View
                                    style={{flexDirection:'row',justifyContent:'center',alignItems:'center',height:45}}>
                                    <Text style={{ color: '#38D68B', fontSize: 16 }}> 查看全部 </Text>
                                    <Image
                                        style={{width: 15, height: 15, marginLeft: 5,marginTop: 2, resizeMode: 'contain'}}
                                        source={require('../../Image/icon_green_arrow.png')}
                                    />
                                </View>
                            </TouchableOpacity>
                            <CommentStarView commentList={this.state.commentList} star={this.state.introduce.star}
                                             id={this.props.ID} type={4}
                                             navigator={this.props.navigator}/>
                        </ParallaxScrollView>
                        :
                        <View style={{flex:1,backgroundColor:'#F5F5F5'}}><View
                            style={{position: 'absolute',top:0,left:0,width:Global.Const.size.width,height:Global.Const.size.height,backgroundColor:null,alignItems:'center',justifyContent:'center'}}>
                            <View
                                style={{backgroundColor:'#333333',borderRadius:5, alignItems: 'center',justifyContent: 'center',width:80,height:80}}>
                                <ActivityIndicator
                                    animating={this.state.animating}
                                    style={{ alignItems: 'center',justifyContent: 'center'}}
                                    size="large"/>
                                <Text style={{color:'white'}}>加载中...</Text>
                            </View>
                        </View>
                        </View>
                }
                <BottomShareView
                    shareTitle={ this.state.introduce.shop_name}
                    shareContent={this.state.introduce.shop_name}
                    shareImageUrl={this.state.images[0]}
                    shareUrl={'http://xc.xiarikui.cn/Api/Index/share'}
                    ref={(ref) => {this.shareView = ref;}}/>
                <BottomCommentBtn navigator={this.props.navigator}
                                  type={4}
                                  rid={this.props.ID}
                                  phone={this.state.phone}
                                  refreshComments={()=>this.refreshComments()}
                />
            </Animated.View>
        )
    }
}

export default FarmHouseSell;